import scale from './scale.js'
import store from '../../../store'
import debounce from './debounce.js'
/**
 * 初始化蓝牙设备
 */
function init(success, fail) {
	uni.openBluetoothAdapter({
		success: e => {
			console.log('初始化蓝牙成功:' + e.errMsg);
			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState(success, fail);
		},
		fail: e => {
			console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
			if (e.errCode !== 0) {
				fail && fail(e.errCode, e.errMsg)
				initTypes(e.errCode, e.errMsg);
			}
		}
	});
}


/**
 * 获取本机蓝牙适配器状态
 */
function getBluetoothAdapterState(success, fail) {
	uni.getBluetoothAdapterState({
		success: res => {
			console.log('获取本机蓝牙适配器状态成功--' + JSON.stringify(res));
			success && success(res)
		},
		fail: e => {
			console.log('获取本机蓝牙适配器状态失败，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				fail && fail(e.errCode, e.errMsg)
				initTypes(e.errCode);
			}
		}
	});
}
/**
 * 初始化蓝牙设备
 */
function openBluetoothAdapter() {
	uni.openBluetoothAdapter({
		success: e => {
			console.log('初始化蓝牙成功:' + e.errMsg);
			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState();
		},
		fail: e => {
			console.log(e)
			console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
			if (e.errCode !== 0) {
				initTypes(e.errCode, e.errMsg);
			}
		}
	});
}
/**
 * 开始搜索蓝牙设备
 */
function startBluetoothDevicesDiscovery(success, fail) {
	uni.startBluetoothDevicesDiscovery({
		success: e => {
			console.log('开始搜索蓝牙设备:' + e.errMsg);
			onBluetoothDeviceFound(success, fail);
		},
		fail: e => {
			console.log('搜索蓝牙设备失败，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				fail && fail(e.errCode)
				initTypes(e.errCode);
			}
		},

	});

}
/**
 * 发现外围设备
 */
function onBluetoothDeviceFound(success, fail) {
	uni.onBluetoothDeviceFound(devices => {
		console.log('开始监听寻找到新设备的事件', devices);
		success && success(devices)
		// getBluetoothDevices(success, fail);
	});

}
/**
 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
 */
function getBluetoothDevices(success, fail) {
	uni.getBluetoothDevices({
		success: res => {
			console.log('获取蓝牙设备成功:' + res.errMsg);
			success && success(res)
		},
		fail: e => {
			console.log('获取蓝牙设备错误，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				fail && fail(e.errCode)
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 停止搜索蓝牙设备
 */
function stopBluetoothDevicesDiscovery(types) {
	return new Promise((result, reject) => {
		uni.stopBluetoothDevicesDiscovery({
			success: e => {
				console.log('停止搜索蓝牙设备:' + e.errMsg);
				result(e.errMsg)
			},
			fail: e => {
				console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
				if (e.errCode !== 0) {
					initTypes(e.errCode);
					reject(e.errCode)
				}
			}
		});
	})

}
/**
 * 断开与低功耗蓝牙设备的连接
 */
function closeBLEConnection(deviceId) {
	uni.closeBLEConnection({
		deviceId,
		success: res => {
			console.log(res);
		},
		fail: e => {
			console.log('断开低功耗蓝牙成功，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}
/**
 * 	断开蓝牙模块
 */
function closeBluetoothAdapter() {
	uni.closeBluetoothAdapter({
		success: res => {
			console.log('断开蓝牙模块成功');
		}
	});
}
/**
 * 引导用户打开APP权限设置界面
 */
function openAppPage() {
	plus.nativeUI.confirm("APP蓝牙权限没有开启，是否去开启？", function(e) {
		if (e.index == 0) {
			if (uni.getSystemInfoSync().platform == 'android') {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			} else if (uni.getSystemInfoSync().platform == 'ios') {
				var UIApplication = plus.ios.import("UIApplication");
				var application2 = UIApplication.sharedApplication();
				var NSURL2 = plus.ios.import("NSURL");
				var setting2 = NSURL2.URLWithString("app-settings:");
				application2.openURL(setting2);
				plus.ios.deleteObject(setting2);
				plus.ios.deleteObject(NSURL2);
				plus.ios.deleteObject(application2);
			}
		}
	}, {
		"buttons": ["Yes", "No"],
		"verticalAlign": "center"
	});
}

/**
 * 引导用户打开相应权限界面
 */
function openPermissionPage() {
	if (uni.getSystemInfoSync().platform == 'android') {
		plus.nativeUI.confirm("手机蓝牙没有开启，是否去开启？", function(e) {
			if (e.index == 0) {
				var main = plus.android.runtimeMainActivity(); //获取activity
				var Intent = plus.android.importClass('android.content.Intent');
				var Settings = plus.android.importClass('android.provider.Settings');
				var intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
				main.startActivity(intent);
			}
		}, {
			"buttons": ["Yes", "No"],
			"verticalAlign": "center"
		});
	} else if (uni.getSystemInfoSync().platform == 'ios') {
		toast('检测蓝牙未开启，请手动开启蓝牙');
	}


}
/**
 * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接，设备丢失，连接异常断开等等
 */
function onBLEConnectionStateChange() {
	uni.onBLEConnectionStateChange(res => {
		// 该方法回调中可以用于处理连接意外断开等异常情况
		console.log(`蓝牙连接状态 -------------------------->`);
		console.log(JSON.stringify(res));
		if (!res.connected) {
			uni.showModal({
				title: '提示',
				content: '监听到蓝牙已断开',
				showCancel: false,
				success: function(res) {
					if (res.confirm) {
						uni.reLaunch({
							url: '../main/main'
						});
					}
				}
			});
		}
	});
}
/**
 * 5.连接低功耗蓝牙
 */
function createBLEConnection(success, fail) {
	uni.createBLEConnection({
		deviceId: store.state.Bluetooth.activeBle.deviceId,
		success: res => {
			//6.获取可写服务
			getBLEDeviceServices(success, fail)
		},
		fail: e => {
			console.log('连接低功耗蓝牙失败，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}
/**
 *7. 获取当前蓝牙所有服务
 */
function getBLEDeviceServices(success, fail) {
	uni.getBLEDeviceServices({
		deviceId: store.state.Bluetooth.activeBle.deviceId,
		success: async res => {
			// console.log(res.services);
			let activeBle = {
				...store.state.Bluetooth.activeBle,
				services: res.services,
				serviceId: '',
				write: {
					characteristicId: '',
				},
				read: { //特征值支持 notify 或者 indicate 
					characteristicId: '',
				}
			}
			store.commit('set_BlueToothActiveBle', activeBle)
			if (store.state.Bluetooth.activeBle.services <= 0) { //获取蓝牙可写服务失败，请重新获取
				//循环获取服务
				debounce(() => {
					getBLEDeviceServices(success, fail)
				}, 500)
				return;
			} else {
				//循环获取服务下的可写特征值
				for (let i = 0; i < store.state.Bluetooth.activeBle.services.length; i++) {
					//获取服务的特征
					await getBLEDeviceCharacteristics(i)
				}
				// console.log('当前服务', JSON.stringify(store.state.Bluetooth.activeBle));
				success && success(store.state.Bluetooth.activeBle)
				// console.log('当前服务可写特征值'+that.activeBle.characteristicId);
				// console.log('当前服务可监听特征值'+that.activeBle.read);
				//8. 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
				// that.notifyBLECharacteristicValueChange()
				// //设置wifi配置
				// that.setWifiConfig()
				// //监听
				// that.readBLECharacteristicValue().then(res => {
				// 	console.log(res);
				// 	if (res.cmd == 1) { //获取wifi列表
				// 		uni.navigateTo({
				// 			url: '../wifi_list/bluetoothWifi?data=' + encodeURIComponent(
				// 				JSON.stringify(res.data))
				// 		})
				// 	}
				// })
			}
		},
		fail: e => {
			console.log('获取设备服务失败，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

/**
 * 获取某个服务下的所有特征值
 */
function getBLEDeviceCharacteristics(index) {
	return new Promise((result, reject) => {
		uni.getBLEDeviceCharacteristics({
			deviceId: store.state.Bluetooth.activeBle.deviceId,
			serviceId: store.state.Bluetooth.activeBle.services[index].uuid,
			success: res => {
				console.log('获取特征值成功:' + store.state.Bluetooth.activeBle.deviceId + JSON.stringify(
					res));
				let activeBle = {
					...store.state.Bluetooth.activeBle,
					characteristics: res.characteristics
				}
				// that.Bluetooth.activeBle.characteristics = res.characteristics;
				if (activeBle.characteristics.length <= 0) {
					console.log('获取特征值失败，请重试!');
					return;
				} else {
					activeBle.serviceId = activeBle.services[index].uuid
					//循环获取服务下的可写特征值
					for (let i = 0; i < activeBle.characteristics.length; i++) {
						if (activeBle.characteristics[i].properties.write) {
							activeBle.write.characteristicId = activeBle.characteristics[i].uuid
						}
						//启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用
						if (activeBle.characteristics[i].properties.notify || activeBle
							.characteristics[i].properties.indicate) {
							activeBle.read.characteristicId = activeBle.characteristics[i].uuid
						}
					}
					result(activeBle)
				}
				store.commit('set_BlueToothActiveBle', activeBle)
				// that.set_BlueToothActiveBle(activeBle)
			},
			fail: e => {
				console.log('获取特征值失败，错误码：' + e.errCode);
				if (e.errCode !== 0) {
					initTypes(e.errCode);
				}
			}
		});
	})
}
//8. 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
function notifyBLECharacteristicValueChange() {
	uni.notifyBLECharacteristicValueChange({
		state: true, // 启用 notify 功能
		deviceId: store.state.Bluetooth.activeBle.deviceId, //蓝牙设备 id
		serviceId: store.state.Bluetooth.activeBle.serviceId, //蓝牙特征值对应服务的 uuid
		characteristicId: store.state.Bluetooth.activeBle.read.characteristicId, //蓝牙特征值的 uuid
		success(res) {
			console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值', res.errMsg)
		},
		fail(e) {
			if (e.errCode !== 0) {
				// initTypes(e.errCode);
			}
		}
	})
}

function readBLECharacteristicValue() {
	return new Promise((result, reject) => {
		let num = 1,
			len = 0,
			cmd = 0,
			allLen = 0,
			Str = ''
		// 13 0001 01 00000002 7b7d
		// onBLECharacteristicValueChange必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
		uni.onBLECharacteristicValueChange(function(characteristic) {
			//arrbuff转成16进制字符串
			let Strin16 = scale.ab2hex(characteristic.value)
			if (num == 1) {
				//拿到body的长度 在把16进制转成10进制
				len = parseInt(Strin16.slice(8, 16), 16)
				cmd = parseInt(Strin16.slice(2, 6), 16)
				//计算16进制字符串的总长度
				allLen = (len + 8) * 2
				console.log('len', len);
				console.log('cmd', cmd);
				console.log('16进制字符串的总长度', allLen);
			}
			if (Str.length < allLen) {
				Str += Strin16
			}
			// 最终接收到的数据
			if (Str.length == allLen) {
				let jsonstr = Str.slice(16, Str.length)
				//16进制转字符串
				let string = scale.hexCharCodeToStr(jsonstr)
				let req = {
					cmd,
					len,
					data: JSON.parse(string)
				}
				result(req)
			}
			num++
		})
		uni.readBLECharacteristicValue({
			deviceId: store.state.Bluetooth.activeBle.deviceId, //蓝牙设备 id
			serviceId: store.state.Bluetooth.activeBle.serviceId, //蓝牙特征值对应服务的 uuid
			characteristicId: store.state.Bluetooth.activeBle.write.characteristicId, //蓝牙特征值的 uuid
			success(res) {
				console.log('readBLECharacteristicValue:', res.errCode)
			}
		})
	})

}
//向低功耗蓝牙设备特征值中写入二进制数据
function writeBLECharacteristicValue(hex) {
	return new Promise((result, reject) => {
		//16进制字符转byte数组
		const arrayBuffer = scale.Str2Bytes(hex)
		//byte数组转成字符串打印出来
		console.log(scale.Bytes2Str(arrayBuffer));
		uni.writeBLECharacteristicValue({
			// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: store.state.Bluetooth.activeBle.deviceId, //蓝牙设备 id
			// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			serviceId: store.state.Bluetooth.activeBle.serviceId, //蓝牙特征值对应服务的 uuid
			// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
			characteristicId: store.state.Bluetooth.activeBle.write.characteristicId, //蓝牙特征值的 uuid
			// 这里的value是ArrayBuffer类型
			value: arrayBuffer,
			success(res) {
				console.log('writeBLECharacteristicValue success', res.errMsg)
				result(res.errMsg)
			},
			fail(err) {
				console.log(err);
				uni.showToast({
					title: '写入失败',
					icon: "none"
				});
				reject(err)
			}
		})
	})
}
/**
 * 判断初始化蓝牙状态
 */
function initTypes(code, errMsg) {
	switch (code) {
		case 10000:
			console.log('未初始化蓝牙适配器');
			openAppPage()
			break;
		case 10001:
			console.log('未检测到蓝牙，请打开蓝牙重试！');
			openPermissionPage()
			break;
		case 10002:
			toast('没有找到指定设备');
			break;
		case 10003:
			toast('连接失败');
			break;
		case 10004:
			toast('没有找到指定服务');
			break;
		case 10005:
			toast('没有找到指定特征值');
			break;
		case 10006:
			toast('当前连接已断开');
			break;
		case 10007:
			toast('当前特征值不支持此操作');
			break;
		case 10008:
			toast('其余所有系统上报的异常');
			break;
		case 10009:
			toast('Android 系统特有，系统版本低于 4.3 不支持 BLE');
			break;
		default:
			toast(errMsg);
	}
}
/**
 * 弹出框封装
 */
function toast(content, showCancel = false) {
	uni.showModal({
		title: '提示',
		content,
		showCancel
	});
}
export default {
	init, //初始化蓝牙
	startBluetoothDevicesDiscovery, //搜索蓝牙设备
	stopBluetoothDevicesDiscovery, //停止搜索蓝牙
	closeBLEConnection, //断开蓝牙
	closeBluetoothAdapter, //断开蓝牙模块
	onBLEConnectionStateChange, //监听蓝牙断开
	writeBLECharacteristicValue, //写入数据
	createBLEConnection, //连接指定特征蓝牙
	notifyBLECharacteristicValueChange, //启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
	readBLECharacteristicValue,//监听蓝牙回复
}
